<?php
include('header.php');
include('geocoder.php');
if ($session->logged_in) {
	if ($session->isAdmin()){ 
		/* 
		 EDIT.PHP
		 Allows user to edit specific entry in database
		*/
		
		 // creates the edit record form
		 // since this form is used multiple times in this file, I have made it a function that is easily reusable
		function renderform( $orgName, $firstName, $lastName, $areaCode, $prefix, $lineNumber, $faxAreaCode, $faxPrefix, $faxLineNumber, $streetAddress, $streetAddress2, $city, $state, $zipCode, $websiteAddress, $email, $times, $additionalInfo, $category, $error)
		{
		?>
		
			<div id="form_container">
			<form id="form" class="appnitro" method="post" action="">
			<?php 
			// if there are any errors, display them
			if ($error != '')
			{
				echo '<div style="padding:4px; border:1px solid red; color:red;">'.$error.'</div>';
			}
		?> 
			<div class="form_description">
			<h2>Organization</h2>
			<p>Edit Selected Organization</p>
			</div>
				<ul>
					<div>* Required</div>
					<!--Orgnanization Name-->
					<li><label class="description">Organization Name *</label>
					
					<span>
						<input class="element text" type="text" name="orgName" value="<?php echo $orgName; ?>"/>
					</span>
					</li>
					
					<!--Contact Information-->
					<li><label class="description">Contact Information *</label>
					
					<!-- First Name -->
					<span>
						<input name="firstName" class="element text" maxlength="255" size="8" value="<?php echo $firstName; ?>" />
						<label>First Name *</label>
					</span>
				
				<!-- Last Name -->
					<span>
						<input name="lastName" class="element text" maxlength="255" size="14" value="<?php echo $lastName; ?>" />
						<label>Last Name *</label>
					</span>
					</li>
					
					<!-- Email -->
					<li>
						<span>
							<input name="email" class="element text large" type="text" maxlength="255" value="<?php echo $email; ?>" />
							<label>Email Address</label>
						</span>
					</li>
					
					<!--Phone and Fax-->
					<li>
					<span>
						<input name="areaCode" type="text" class="element text" value="<?php echo $areaCode; ?>" size="3" /> 
						-
					<label>Phone *</label>
					</span>
					<span>
						<input name="prefix" class="element text" size="3" maxlength="3" value="<?php echo $prefix; ?>" type="text"> -
					</span>
					<span>
						<input name="lineNumber" class="element text" size="4"maxlength="4"value="<?php echo $lineNumber; ?>" type="text">
					</span>
					</li>
					<li>
					<span>
						<input name="faxAreaCode" class="element text" size="3" maxlength="3" value="<?php echo $faxAreaCode; ?>" type="text"> -
						<label>Fax</label>
					</span>
					<span>
						<input name="faxPrefix" class="element text" size="3" maxlength="3" value="<?php echo $faxPrefix; ?>" type="text"> -
					</span>
					<span>
						<input name="faxLineNumber" class="element text" size="4" maxlength="4"value="<?php echo $faxLineNumber; ?>" type="text">
					</span>
					</li>
					
					<!-- Address -->
					<li><label class="description">Address</label>
					<span>
						<input name="streetAddress" class="element text" value="<?php echo $streetAddress; ?>" type="text">
						<label>Street Address *</label>
					</span>
					<span>
						<input name="streetAddress2" class="element text" value="<?php echo $streetAddress2; ?>" type="text">
						<label>Address Line 2</label>
					</span>
					</li>
					<li>
					<span>
						<input name="city" class="element text" size="10" maxlength="30" value="<?php echo $city; ?>" type="text"> -
						<label>city *</label>
					</span>
					<span>
						<input name="state" class="element text" size="3" maxlength="15" value="<?php echo $state; ?>" type="text"> -
						<label>state *</label>
					</span>
					<span>
						<input name="zipCode" class="element text" size="4"maxlength="15"value="<?php echo $zipCode; ?>" type="text">
						<label>Zip Code *</label>
					</span>
					</li>
					
					<!--Website Address-->
					<li><label class="description">Website Address</label>
					<span>
						<input class="element text" name="websiteAddress" value="<?php echo $websiteAddress; ?>" type="text" />
					</span>
					</li>
					
					<!-- Organization type -->
					<li>
						<label class="description">Organization Type *</label>
						<div>
                        <!--Function for displaying the Organization Type-->
                        <?php function org_type_select($default_value='') 
							{
								$select = '<select name="category">';
								$options = array('other','farm','farmers_market','community_garden','orchard','csa',);
								//$displays = array('Other','Farm',"Farmer's Market",'Community Garden','Orchard','CSA',);
								foreach($options as $option) 
								{
									$select .= write_option($option, $option, $default_value);
								}
								$select .= '</select>';
								return $select;  
							}
							
							function write_option($value, $display, $default_value='') 
							{
								$option = '<option value="'.$value.'"';
								$option .= ($default_value == $value) ? ' SELECTED' : '';
								$option .= '>'.$display.'</option>';
								return $option;
							}
						 echo org_type_select($category); ?>
						<!--<select name="category" >
                        	<option value="$category">Currrent: <?php echo $category ?></option>
							<option value="farm" >Farm</option>
							<option value="farmers_market">Farmer's Market</option>
							<option value="community_garden">Community Garden</option>
							<option value="orchard">Orchard</option>
							<option value="csa">CSA</option>
							<option value="other">Other</option>
						</select>    -->            
						</div>
					</li>
					
					<!-- times-->
					<li>
					<label class="description" >Times available *</label>
					<div>
						<textarea name="times" class="element textarea medium" ><?php echo $times ?></textarea>
					</div>
					<p class="guidelines">
					<small>
							Please enter the days of the week 	and times you are avaialable.
					</small>
					</p>
					</li>
					
					<!-- Additional Information -->
					<li><label class="description">Additional information </label>
						<div>
							<textarea name="additionalInfo" class="element textarea medium"><?php echo $additionalInfo ?></textarea>
						</div>
						<p class="guidelines">
							<small>
								Is there anything other information you would like to add?
							</small>
						</p>
					</li>
		
					<li class="button">
						<input class="button_text" type="submit" name="submit" value="Submit" />
						<input class="button_text" type="button" name="cancel" value="Cancel" onclick="location.href = 'javascript:history.back(1)'"/>
					</li>
				</ul>
			</form> 
			</div>
		
		<?php
		include('footer.php');
		}

		// check if the form has been submitted. If it has, process the form and save it to the database
		if (isset($_POST['submit']))
		{ 
			// confirm that the 'id' value is a valid integer before getting the form data
			if (is_numeric($_GET['id']))
			{
				// get form data, making sure it is valid
				$orgID = $_GET['id'];		
				$orgName = mysql_real_escape_string(($_POST['orgName']));
				$firstName = mysql_real_escape_string(($_POST['firstName']));
				$lastName = mysql_real_escape_string(($_POST['lastName']));
				$areaCode = mysql_real_escape_string(($_POST['areaCode']));
				$prefix = mysql_real_escape_string(($_POST['prefix']));
				$lineNumber = mysql_real_escape_string(($_POST['lineNumber']));
				$faxAreaCode = mysql_real_escape_string(($_POST['faxAreaCode']));
				$faxPrefix = mysql_real_escape_string(($_POST['faxPrefix']));
				$faxLineNumber = mysql_real_escape_string(($_POST['faxLineNumber']));
				$streetAddress = mysql_real_escape_string(($_POST['streetAddress']));
				$streetAddress2 = mysql_real_escape_string(($_POST['streetAddress2']));
				$city = mysql_real_escape_string(($_POST['city']));
				$state = mysql_real_escape_string(($_POST['state']));
				$zipCode = mysql_real_escape_string(($_POST['zipCode']));
				$websiteAddress = mysql_real_escape_string(($_POST['websiteAddress']));
				$email = mysql_real_escape_string(($_POST['email']));
				$times = mysql_real_escape_string(($_POST['times']));
				$additionalInfo = mysql_real_escape_string(($_POST['additionalInfo']));
				$category = mysql_real_escape_string(($_POST['category']));
				// geocode function
				$address = $streetAddress . " " . $streetAddress2 . " " . $zipCode;
					$geocodeAddress = preg_replace ( '/\s+/', '+', $address );
					$geocode = geocode ( $geocodeAddress );
					$lat = $geocode ["lat"];
					$lng = $geocode ["lng"];
					
		
				// check that required fields are all filled in
				if ($orgName == '' || $firstName == '' || $lastName == '' || $areaCode == '' || $prefix == '' || $lineNumber == '' || $streetAddress == '' || $city == '' || $state == '' || $zipCode == '' || $category == '')
				{
					// generate error message
					$error = 'ERROR: Please fill in all required fields!';
		
					//error, display form
					renderform( $orgName, $firstName, $lastName, $areaCode, $prefix, $lineNumber, $faxAreaCode, $faxPrefix, $faxLineNumber, $streetAddress, $streetAddress2, $city, $state, $zipCode, $websiteAddress, $email, $times, $additionalInfo, $category, $error);
				}
				else
				{
					// save the data to the database
					mysql_query("UPDATE organizations 
					SET 
					orgName = '$orgName', 
					firstName = '$firstName', 
					lastName = '$lastName',
					areaCode = '$areaCode', 
					prefix = '$prefix', 
					lineNumber = '$lineNumber',
					faxAreaCode = '$faxAreaCode',
					faxPrefix = '$faxPrefix',
					faxLineNumber = '$faxLineNumber',
					streetAddress = '$streetAddress', 
					streetAddress2 = '$streetAddress2', 
					city = '$city', 
					state = '$state', 
					zipCode = '$zipCode',
					websiteAddress = '$websiteAddress',
					email = '$email',
					times = '$times',
					additionalInfo = '$additionalInfo',
					lat = '$lat',
					lng = '$lng',
					category = '$category'
					WHERE orgID = '$orgID'")
					or die(mysql_error()); 
		
					// once saved, redirect back to the edit page
					header('refresh: 5; url=');?>
					
                    <div id="form_container">
					<form id="form" class="appnitro">
                        <div class="form_description">
							<h2 style="padding:4px; border:1px solid green; color:green;">Update Successfully</h2>
							<p>One Record was Updated</p>
						</div>
						<ul>
							<li>You will be re-directed to the page you were on in 5 seconds...</li>
						</ul>
					</form>
					</div>
				<?php 
				include("footer.php");
				}
			}
			else {// if the 'id' isn't valid, display an error ?>
				<div id="form_container">
				<form id="form" class="appnitro">
					<div class="form_description">
						<h2 style="padding:4px; border:1px solid red; color:red;">Error</h2>
						<p>"The ID is invalid"</p>
					</div>
				</form>
				</div>;
			<?php 
			include("footer.php");
			}
		}
		else {// if the form hasn't been submitted, get the data from the db and display the form
		
			// get the 'id' value from the URL (if it exists), making sure that it is valid (checking that it is numeric/larger than 0)
			if (isset($_GET['id']) && is_numeric($_GET['id']) && $_GET['id'] > 0) {
				// query db
				$orgID = $_GET['id'];
				$result = mysql_query("SELECT * FROM organizations WHERE orgID='$orgID'")
				or die(mysql_error()); 
				$row = mysql_fetch_array($result);
		
				// check that the 'id' matches up with a row in the databse
				if($row) {
					// get data from db
					$orgName = $row['orgName'];
					$firstName = $row['firstName'];
					$lastName = $row['lastName'];
					$areaCode = $row['areaCode'];
					$prefix = $row['prefix'];
					$lineNumber = $row['lineNumber'];
					$faxAreaCode = $row['faxAreaCode'];
					$faxPrefix = $row['faxPrefix'];
					$faxLineNumber = $row['faxLineNumber'];
					$streetAddress = $row['streetAddress'];
					$streetAddress2 = $row['streetAddress2'];
					$city = $row['city'];
					$state = $row['state'];
					$zipCode = $row['zipCode'];
					$websiteAddress = $row['websiteAddress'];
					$email = $row['email'];
					$times = $row['times'];
					$additionalInfo = $row['additionalInfo'];
					$category = $row['category'];
					
		
					// show form
					renderform( $orgName, $firstName, $lastName, $areaCode, $prefix, $lineNumber, $faxAreaCode, $faxPrefix, $faxLineNumber, $streetAddress, $streetAddress2, $city, $state, $zipCode, $websiteAddress, $email, $times, $additionalInfo, $category, '');
				}
				else {// if no match, display result?>
					<div id="form_container">
					<form id="form" class="appnitro">
						<div class="form_description">
							<h2 style="padding:4px; border:1px solid red; color:red;">No Record Found</h2>
							<p>"This Organization Doesn't Exist on Our Database"</p>
						</div>
						<ul>
							<li>Add This Organization <a href="new_org_register.php">Here</a></li>
						</ul>
					</form>
					</div>;
				<?php }
			}
			else {// if the 'id' in the URL isn't valid, or if there is no 'id' value, display an error?>
				<div id="form_container">
				<form id="form" class="appnitro">
					<div class="form_description">
						<h2 style="padding:4px; border:1px solid red; color:red;">Error</h2>
						<p>"This URL is invalid"</p>
					</div>
				</form>
				</div>;
			<?php }
		}
	}
	else {
		include('header.php');?>
		<div id="form_container">
		<form id="form" class="appnitro">
		<div class="form_description">
		<h2 style="padding:4px; border:1px solid red; color:red;">Access Denied!</h2>
		<p><?php echo ADMIN_NOT_ADMIN; ?></p>
		</div>
		</form>
		</div>	
<?php	include('footer.php');
	}
}
else {
	include('header.php');?>

	<div id="form_container">
    <form id="form" class="appnitro">
    <div class="form_description">
    <h2>Access Denied!</h2>
    <p><?php echo ADMIN_NOT_LOGGED; ?></p>
    </div>
    </form>
    </div>
<?php
	include('footer.php');
}
?>